﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace 多协议通信平台.Common
{
    public class AttachHelper
    {
        public static string GetPassword(DependencyObject obj)
        {
            return (string)obj.GetValue(PasswordProperty);
        }

        public static void SetPassword(DependencyObject obj, string value)
        {
            obj.SetValue(PasswordProperty, value);
        }

        public static readonly DependencyProperty PasswordProperty =
            DependencyProperty.RegisterAttached("Password", typeof(string), typeof(AttachHelper), new PropertyMetadata("",PasswordChanged));

        static bool isUpdating = false;
        /// <summary>
        /// pass the changed value from datasource(view model) to ui
        /// </summary>
        /// <param name="d"></param>
        /// <param name="e"></param>
        private static void PasswordChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (isUpdating)
                return;
            PasswordBox? pd = d as PasswordBox;
            pd.PasswordChanged -= Pd_PasswordChanged;
            pd.Password = e.NewValue?.ToString();
            pd.PasswordChanged += Pd_PasswordChanged;
        }

        /// <summary>
        ///  pass ui value to datasource(view model)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void Pd_PasswordChanged(object sender, RoutedEventArgs e)
        {
            isUpdating = true;
            PasswordBox? pd = sender as PasswordBox;
            SetPassword(pd, pd.Password);
            isUpdating = false;
        }
    }
}
